package com.polaris.live.dialog_fragment

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import androidx.collection.arrayMapOf
import androidx.core.view.get
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.Utils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.adapter.gift.GiftBannerAdapter
import com.polaris.live.adapter.gift.GiftHeadAdapter
import com.polaris.live.adapter.gift.GiftIndicatorAdapter
import com.polaris.live.adapter.gift.GiftPagerAdapter
import com.polaris.live.adapter.gift.GiftPagerBackPackAdapter
import com.polaris.live.adapter.gift.GiftTitleAdapter
import com.polaris.live.adapter.gift.GiftWallSelectNumAdapter
import com.polaris.live.adapter.recharge.RechargeBannerAdapter
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.PopupGiftBinding
import com.polaris.live.dialog.ToolSureDialog
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.net.homeService
import com.polaris.live.net.userService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.SendGiftSurePopup
import com.polaris.live.resp.back_resp.GiftBannerVo
import com.polaris.live.resp.back_resp.GiftBean
import com.polaris.live.resp.back_resp.UserBackpackGiftResp
import com.polaris.live.resp.bean.GiftSendBean
import com.polaris.live.resp.bean.GiftSendTitleBean
import com.polaris.live.resp.go_resp.UseConsumableRequest
import com.polaris.live.translation.R.string
import com.polaris.live.ui.message.MessageActivity
import com.polaris.live.ui.message.fragment.dialog.BottomDialogFragment
import com.polaris.live.ui.party.widget.seat.bean.BaseSeatBean
import com.polaris.live.ui.party.widget.seat.bean.GiftSeatBean
import com.polaris.live.utils.CommonUtils.arReverse
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.high_light.HighlightPro
import com.polaris.live.widget.high_light.parameter.Constraints
import com.polaris.live.widget.high_light.parameter.HighlightParameter
import com.polaris.live.widget.high_light.parameter.MarginOffset
import com.polaris.live.widget.high_light.shape.RectShape
import com.polaris.live.widget.refresh.EmptyView
import com.zhpan.indicator.enums.IndicatorSlideMode
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.util.Collections
import kotlin.math.max

/**
 * 礼物弹窗，这个fragment默认是不复用的[isReusable]
 *
 * @author Created by lucas on 2023/10/28 10:52
 */
class GiftDialogFragment(
    private val showType: Int = AppConst.GiftComming.LIVE,
    private val sourceType: Int = AppConst.BackpackGiftComming.MESSAGE,
    private val anchorId: Long? = null,
    //会复用的默认使用直播的，其实这个也是显示不了的
    override val isReusable: Boolean = false,
    private val dismiss: (() -> Unit)? = null,
    private val onShowProfileClick: ((infoOtherResp: UserBasicVo) -> Unit)? = null,
    private val partySendGiftCallback: ((giftSendBean: GiftSendBean, selectUser: List<Long>) -> Unit)? = null,
    private val sendGiftCallback: ((giftSendBean: GiftSendBean) -> Unit)? = null,
) : BottomDialogFragment() {

    private var isShowSendGiftSurePopup = false

    private lateinit var mBinding: PopupGiftBinding

    private val mViewModel by viewModels<BaseViewModel>()

    private val mData: List<GiftBean> by lazy {
        CommonCache.getGiftResp()?.find {
            showType == it.showType
        }?.gifts ?: emptyList()
    }

    private var backPackList: MutableList<UserBackpackGiftResp> = mutableListOf() //背包礼物

    private val mGiftPagerBackPackAdapter by lazy { GiftPagerBackPackAdapter() } //背包礼物Adapter

    private var isShowBackPack = false //是否显示背包

    private val emptyView by lazy { EmptyView(requireContext()) }

    private val mNumAdapter by lazy { GiftWallSelectNumAdapter() }

    private val mIndicator by lazy { GiftIndicatorAdapter() }

    private val mHeadAdapter by lazy { GiftHeadAdapter() }

    private val mBannerAdapter by lazy { RechargeBannerAdapter() }

    private val mGiftBannerAdapter by lazy { GiftBannerAdapter() }

    private val mTitleList = mutableListOf<GiftSendTitleBean>()
    private val mTitleAdapter by lazy { GiftTitleAdapter() }

    private var mAvatar: String? = null
    private var mAvatarFrame: String? = null
    private var mOtherId: Long? = null
    private var mOtherName: String? = null

    //派对点击某人送礼
    private var mInfoOther: UserBasicVo? = null

    //派对麦上列表
    private var mSeatList: MutableList<BaseSeatBean>? = null

    //房主id
    private var mHomeOwner: Long? = null

    //存储选中的礼物信息
    private var giftSendBean: GiftSendBean? = null

    private var mGiftId: Long = -1//选中的礼物id
    private var mGiftType: Int = -1//选中的列表

    override fun initImmersionBar() {
        if (sourceType == AppConst.BackpackGiftComming.MESSAGE) {
            ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .transparentNavigationBar()
                .navigationBarDarkIcon(false)
                .init()
        } else {
            ImmersionBar.with(this)
                .transparentBar()
                .navigationBarDarkIcon(false)
                .init()
        }
    }

    override fun setStyle() {
        val styleId = if (sourceType == AppConst.BackpackGiftComming.MESSAGE) {
            R.style.DialogFragmentBottomGiftDialogBlack
        } else {
            R.style.DialogFragmentBottomGiftDialog
        }
        setStyle(STYLE_NO_FRAME, styleId)
    }

    override fun getDialogHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    private var timeJob: Job? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        return PopupGiftBinding.inflate(inflater, container, false).let {
            mBinding = it
            it.root
        }
    }

    /**
     * 更新礼物数量总数服务器返回
     */
    fun upBackpackIdAllCount(backpackId: Long, count: Long) {
        val index = backPackList.indexOfFirst { it.backpackId == backpackId }
        if (index != -1) {
            val data = backPackList.getOrNull(index)
            if (data != null) {
                val data2 = data.copy(amount = count)
                if (count <= 0) {
                    backPackList.removeAt(index)
                } else {
                    backPackList[index] = data2
                }
            }
            initTitleGiftBackPack(backPackList)
        } else {
            if (count > 0) {
                getBackpackGifts(sourceType)
            }
        }
    }

    /**
     * 更新礼物数量
     */
    fun upBackpackIdCount(backpackId: Long, count: Int) {
        val index = backPackList.indexOfFirst { it.backpackId == backpackId }
        if (index != -1) {
            val data = backPackList.getOrNull(index)
            if (data != null) {
                val data2 = data.copy(amount = data.amount + count)
                if (data.amount + count <= 0) {
                    backPackList.removeAt(index)
                } else {
                    backPackList[index] = data2
                }
            }
        }
        initTitleGiftBackPack(backPackList)
    }

    /**
     * 不在直播 游戏  派对
     */
    private val noLiveOrGameOrParty =
        showType != AppConst.GiftComming.LIVE && showType != AppConst.GiftComming.GAME && showType != AppConst.GiftComming.PARTY

    /**
     * 初始化头部需要显示的item
     */
    private fun initTitle() {
        if (noLiveOrGameOrParty) {
            val commonList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.NORMAL_GIFT }
            val customizedGiftList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.CUSTOMIZED }
            val giftPrivilegeList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.GIFT_PRIVILEGE }
            if (commonList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.common_gift),
                        DIALOG_COMMON,
                        GiftPagerAdapter(),
                        mBinding.viewPageCommon,
                        filterGift(LiveConst.GiftType.NORMAL_GIFT)
                    )
                )
            }
            if (customizedGiftList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.customized_gift),
                        DIALOG_CUSTOMIZED,
                        GiftPagerAdapter(),
                        mBinding.viewPageCustomized,
                        filterGift(LiveConst.GiftType.CUSTOMIZED)
                    )
                )
            }
            if (giftPrivilegeList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.gift_of_privilege),
                        DIALOG_GIFT_PRIVILEGE,
                        GiftPagerAdapter(),
                        mBinding.viewPagePrivilege,
                        filterGift(LiveConst.GiftType.GIFT_PRIVILEGE)
                    )
                )
            }
        } else {
            val luckList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.LUCK_GIFT }
            val commonList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.NORMAL_GIFT }
            val gameList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.GAME_BEANS_GIFT }
            val customizedGiftList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.CUSTOMIZED }
            val giftPrivilegeList =
                mData.indexOfFirst { gift -> gift.type == LiveConst.GiftType.GIFT_PRIVILEGE }

            if (luckList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.luck_gift),
                        DIALOG_LUCK,
                        GiftPagerAdapter(),
                        mBinding.viewPage,
                        filterGift(LiveConst.GiftType.LUCK_GIFT)
                    )
                )
            }
            if (commonList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.common_gift),
                        DIALOG_COMMON,
                        GiftPagerAdapter(),
                        mBinding.viewPageCommon,
                        filterGift(LiveConst.GiftType.NORMAL_GIFT)
                    )
                )
            }
            if (gameList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.game_beans_gift),
                        DIALOG_GAME,
                        GiftPagerAdapter(),
                        mBinding.viewPageGame,
                        filterGift(LiveConst.GiftType.GAME_BEANS_GIFT)
                    )
                )
            }
            if (customizedGiftList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.customized_gift),
                        DIALOG_CUSTOMIZED,
                        GiftPagerAdapter(),
                        mBinding.viewPageCustomized,
                        filterGift(LiveConst.GiftType.CUSTOMIZED)
                    )
                )
            }
            if (giftPrivilegeList != -1) {
                mTitleList.add(
                    GiftSendTitleBean(
                        StringUtils.getString(string.gift_of_privilege),
                        DIALOG_GIFT_PRIVILEGE,
                        GiftPagerAdapter(),
                        mBinding.viewPagePrivilege,
                        filterGift(LiveConst.GiftType.GIFT_PRIVILEGE)
                    )
                )
            }
        }
        mTitleAdapter.setList(mTitleList)
        if (noLiveOrGameOrParty) {
            mTitleAdapter.setSelectType(DIALOG_COMMON)
        } else {
            mTitleAdapter.setSelectType(DIALOG_LUCK)
        }
        mTitleList.forEach {
            initPage(it.data, it.viewPager2, it.adapter)
        }
        showViewPager(mTitleAdapter.getSelectType())
    }

    private fun showViewPager(type: Int) {
        mTitleList.forEach {
            if (it.type == type) {
                it.viewPager2.visibility = View.VISIBLE
            } else {
                it.viewPager2.visibility = View.GONE
            }
        }

    }

    private fun getAdapter(type: Int): GiftPagerAdapter? {
        if (type < 0) {
            return null
        } else {
            mTitleList.forEach {
                if (it.type == type) {
                    return it.adapter
                }
            }
        }
        return null
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        NavigationBarUtils.setNavigationHeight(mBinding.llBottom)
        giftSendBean = null
        mTitleList.clear()
        initTitle()

        mBinding.giftTitleRecycler.visibility = View.VISIBLE

        mBinding.inclndicator.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            adapter = mIndicator
        }
        mBinding.numRecycler.apply {
            adapter = mNumAdapter
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        }
        mBinding.headRecycler.apply {
            adapter = mHeadAdapter
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            itemAnimator = null
        }
        mBinding.giftTitleRecycler.apply {
            adapter = mTitleAdapter
            itemAnimator = null
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        }

        mBinding.viewPageBackpack.apply {
            adapter = mGiftPagerBackPackAdapter
            offscreenPageLimit = 1
            (getChildAt(0) as RecyclerView).itemAnimator = null
        }
        mBinding.giftBannerView.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mGiftBannerAdapter)
            setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
            setIndicatorVisibility(View.GONE)
            setRoundCorner(12.dp)
            setScrollDuration(500)
            setOnPageClickListener { clickedView, position ->
                if (!LiveStateManager.isCalling()) {
                    val data = mBinding.giftBannerView.data.getOrNull(position) ?: return@setOnPageClickListener
                    if (data is GiftBannerVo) {
                        data.router?.let {
                            RouterUtils.routerGoto(it)
                        }
                    }
                }
            }
        }
        emptyView.setEmptyTip(
            R.drawable.salalogo,
            StringUtils.getString(string.backpack_null),
            ColorUtils.getColor(R.color.color_ffffff_40),
            40.autoDp,
            40.autoDp
        )
        mGiftPagerBackPackAdapter.setEmptyView(emptyView)

        mNumAdapter.setList(NUM_LIST)


        mAvatar?.also { setAvatar(it, mAvatarFrame) }
        mOtherId?.also { setUserId(it, mOtherName) }
        mInfoOther?.let { setPartySomeOne(it) }
        mSeatList?.let { mHomeOwner?.let { it1 -> setPartyAll(it, it1) } }

        onShow()

        initListener()
        setIndicator()

        initBanner(CommonConst.BannerType.BANNER_GIFT_TOP)
        getBackpackGifts(sourceType)
        mBinding.root.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                showGuide()
                mBinding.root.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }

        })
    }

    /**
     * 设置指示器
     */
    private fun setIndicator() {
        if (isShowBackPack) {
            mIndicator.setList(Collections.nCopies(mGiftPagerBackPackAdapter.data.size, ""))
        } else {
            getAdapter(mTitleAdapter.getSelectType())?.let {
                mIndicator.setList(Collections.nCopies(it.data.size, ""))
            }
        }
    }

    private fun startTime() {
        getBackGiftRed()
        cancelTime()
        timeJob = mViewModel.viewModelScope.launch {
            while (isActive) {
                delay(6000)
//                val nowServerTime = CacheUtil.getServerTime()
//                backPackList = backPackList.filter {
//                    (it.expiredTime == null) || (it.expiredTime.toLong() - nowServerTime > 0)
//                }.toMutableList()
//                initTitleGiftBackPack(backPackList)
                timerUpdate()
            }
        }
    }

    private fun timerUpdate() {
        val nowServerTime = CacheUtil.getServerTime()
        backPackList = backPackList.mapNotNull { item ->
            when {
                item.expiredTime == null -> item // 永久物品
                item.amount > 1 -> { //聚合物品
                    val remainingTime = item.expiredTime.toLong().minus(nowServerTime)
                    if (remainingTime < 0) { //超時刪除第一個
                        val bcr = item.getUserBackpackConsumableResp()
                        if (bcr != null) {
                            bcr.backpackIds.remove(item.backpackId)
                            bcr.expiredTimes.removeAt(0)
                            val newBackpackId = bcr.backpackIds.firstOrNull()
                            val newContext = JsonUtils.toJson(bcr)
                            if (newBackpackId != null) {
                                item.copy(
                                    amount = bcr.backpackIds.size.toLong(),
                                    backpackId = newBackpackId,
                                    expiredTime = bcr.expiredTimes.firstOrNull(),
                                    content = newContext,
                                )
                            } else null
                        } else null
                    } else item
                }

                item.expiredTime.toLong() - nowServerTime > 0 -> item // 未超时
                else -> null
            }
        }.toMutableList()
        initTitleGiftBackPack(backPackList)
    }

    private fun cancelTime() {
        timeJob?.cancel()
        timeJob = null
    }

    private fun initBanner(type: Int) {
        mViewModel.request(
            { homeService.getBannerList(type) },
            {
                if (it.isNotEmpty()) {
                    mBinding.bannerView.apply {
                        registerLifecycleObserver(lifecycle)
                        setAdapter(mBannerAdapter)
                        setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
                        setIndicatorVisibility(View.GONE)
                        setRoundCorner(12.dp)
                        setScrollDuration(500).create(it)
                        visibility = View.VISIBLE
                    }
                }
            })
    }

    /**
     * 获取礼物红点
     */
    private fun getBackGiftRed() {
        mViewModel.request(
            { userService.getHaveNewBackpack() }, {
                mBinding.backpackRed.visibility = if (it) View.VISIBLE else View.GONE
            })
    }

    /**
     * 去除礼物红点
     */
    private fun putBackGiftRed() {
        mBinding.backpackRed.visibility = View.GONE
        mViewModel.request(
            { userService.putHaveNewBackpack(arrayMapOf("a" to "a")) }, {
            })
    }

    /**
     * 获取背包礼物
     */
    private fun getBackpackGifts(type: Int) {
        mViewModel.request({ userService.backpackGifts(type) }, {
            if (it.isNotEmpty()) {
                initTitleGiftBackPack(it)
            }
        })
    }

    //所有监听
    private fun initListener() {
        mBinding.allTv.setOnSingleClickListener {
            giftSendBean?.let { da ->
                val num = backPackList.find { it.backpackId == da.backpackId }?.amount
                val times = num?.toInt() ?: 1
                mGiftPagerBackPackAdapter.updateTimes(times)
                mBinding.allTv.setBackgroundResource(R.drawable.r24_back_fe1849)
                mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.white))
                mNumAdapter.setSelect(-1)
                da.isAll = true
                da.num = times
            }
        }
        mBinding.knapsackImg.setOnSingleClickListener {
            mBinding.giftBannerView.visibility = View.GONE
            giftSendBean = null
            isShowBackPack = true
            putBackGiftRed()
            getBackpackGifts(sourceType)
            showViewPager(-1)
            mTitleAdapter.setSelectType(-1)
            mBinding.viewPageBackpack.visibility = View.VISIBLE
            mBinding.allTv.visibility = View.VISIBLE
            mBinding.giftSelectImg.visibility = View.GONE
            mBinding.allTv.background = null
            mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.fff_70))
            mBinding.knapsackImg.setImageResource(R.drawable.ic_knapsack_open)
            switchGiftNumState(false)
            hideSoftInput()

            if (mGiftPagerBackPackAdapter.data.isEmpty()) {    //这个页面没有背包礼物数据
                mIndicator.setList(emptyList())
            } else {
                mIndicator.setList(Collections.nCopies(mGiftPagerBackPackAdapter.data.size, ""))
                val currentItem = mBinding.viewPageBackpack.currentItem
                mIndicator.setSelect(currentItem)

                val indexPage = mGiftPagerBackPackAdapter.getIndexPage()
                val selectPosition = mGiftPagerBackPackAdapter.getSelectPosition()
                if (indexPage == -1 || selectPosition == -1) { //没有选中任何礼物
                    val twoData = mGiftPagerBackPackAdapter.data.getOrNull(0)
                    if (!twoData.isNullOrEmpty()) { //找到数据再设置为默认为0的位置
                        val nowData = twoData[0]
                        mGiftPagerBackPackAdapter.reset()
                        giftSendBean = GiftSendBean(
                            nowData.backpackType,
                            nowData.getGiftBeanNoNull(),
                            1,
                            backpackId = nowData.backpackId
                        )
                        setDescription(nowData.description)
                    }
                } else {
                    //这个页面选中的数据
                    val selectData = mGiftPagerBackPackAdapter.getAdapter(indexPage)?.getItemOrNull(selectPosition)
                    if (selectData != null) { //选中有效
                        mGiftPagerBackPackAdapter.updateTimes(1)
                        giftSendBean = GiftSendBean(
                            selectData.backpackType,
                            selectData.getGiftBeanNoNull(),
                            1,
                            backpackId = selectData.backpackId
                        )
                        setDescription(selectData.description)
                    } else {
                        val twoData = mGiftPagerBackPackAdapter.data.getOrNull(0)
                        if (!twoData.isNullOrEmpty()) { //找到数据再设置为默认为0的位置
                            val nowData = twoData[0]
                            mGiftPagerBackPackAdapter.reset()
                            giftSendBean = GiftSendBean(
                                nowData.backpackType,
                                nowData.getGiftBeanNoNull(),
                                1,
                                backpackId = nowData.backpackId
                            )
                            setDescription(nowData.description)
                        }
                    }
                }

            }
            selectInit()
        }
        mBinding.frameLayout.setOnSingleClickListener {
            hide()
            cancelTime()
            dismiss?.invoke()
        }
        mBinding.lookUserProfile.setOnSingleClickListener {
            mInfoOther?.let {
                onShowProfileClick?.invoke(it)
                hide()
                cancelTime()
                dismiss?.invoke()
            }
        }
        mTitleList.forEach { bean ->
            bean.adapter.setOnGiftItemClickListener { it, index, position ->
                val mSelectedGiftItem = it.getItem(position)
                //用户切换礼物后赠送数量回到1
                bean.adapter.updateIndex(index, position)
                bean.adapter.updateTimes(1)
                mNumAdapter.setSelect(0)
                switchGiftNumState(false)
                giftSendBean =
                    GiftSendBean(
                        BACKPACK_GIFT,
                        mSelectedGiftItem,
                        1,
                        backpackId = null
                    )
                hideSoftInput()
                showGiftBanner(mSelectedGiftItem.banner)
            }
        }
        mGiftPagerBackPackAdapter.setOnGiftBackPackItemClickListener { it, index, position ->
            val item = it.getItem(position)
            mBinding.allTv.background = null
            mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.fff_70))
            //用户切换礼物后赠送数量回到1
            mGiftPagerBackPackAdapter.updateIndex(index, position)
            mGiftPagerBackPackAdapter.updateTimes(1)
            mNumAdapter.setSelect(0)
            switchGiftNumState(false)
            giftSendBean =
                GiftSendBean(
                    item.backpackType,
                    item.getGiftBeanNoNull(),
                    1,
                    backpackId = item.backpackId
                )
            if (item.description.isNullOrEmpty()) {
                mBinding.sourceTv.visibility = View.GONE
            } else {
                mBinding.sourceTv.visibility = View.VISIBLE
                mBinding.sourceTv.text = item.description
            }
            hideSoftInput()

            if (item.backpackType == BACKPACK_TOOL) {
                val user = if (mBinding.headRecycler.isVisible) {
                    mHeadAdapter.getSelectUserBasic().getOrNull(0)
                } else {
                    if (mInfoOther != null) {
                        mInfoOther
                    } else if (mOtherId == null) {
                        null
                    } else {
                        UserBasicVo(
                            mOtherId ?: 0,
                            0,
                            0,
                            mAvatar ?: "",
                            mOtherName ?: "",
                            null,
                            0,
                            0,
                            null,
                            null,
                            null,
                            null,
                            null,
                            mAvatarFrame,
                            0,
                            0, official = 0
                        )
                    }

                }
                if (user != null) {
                    XPopup.Builder(context)
                        .moveUpToKeyboard(false)
                        .isDestroyOnDismiss(true)
                        .asCustom(
                            ToolSureDialog(
                                requireContext(),
                                user,
                                item.getUserBackpackConsumableResp()?.description ?: ""
                            ) {
                                useConsumable(item.backpackId, user.userId)
                            }
                        )
                        .show()
                } else {
                    ToastGravity.showGravity(StringUtils.getString(string.no_one_selected_for_use))
                }

            }
        }

        mNumAdapter.setOnItemClickListener { _, _, position ->
            //背包切换数量
            if (isShowBackPack) {
                val clickNum = NUM_LIST[position]
                val num = backPackList.find { it.backpackId == giftSendBean?.backpackId }?.amount
                val times = if (num == null) {
                    clickNum
                } else {
                    if (num.toInt() < clickNum) {
                        num.toInt()
                    } else {
                        clickNum
                    }
                }
                mGiftPagerBackPackAdapter.updateTimes(times)
                giftSendBean?.apply {
                    this.num = mGiftPagerBackPackAdapter.getSelectTimes()
                    this.isAll = false
                }

                mBinding.allTv.background = null
                mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.fff_70))
            } else {
                getAdapter(mTitleAdapter.getSelectType())?.apply {
                    updateTimes(NUM_LIST[position])
                    giftSendBean?.apply {
                        this.num = getSelectTimes()
                    }
                }

            }
            mNumAdapter.setSelect(position)
            switchGiftNumState(false)

            hideSoftInput()
        }

        mBinding.giftSelectImg.setOnSingleClickListener {
            //显示软键盘
            switchGiftNumState(true)
            mNumAdapter.setSelect(-1)
            showSoftInput()
        }

        //输入框
        mBinding.giftNumEdit.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                val toString = mBinding.giftNumEdit.text.toString()
                if (toString.isNotEmpty()) {
                    var sendTimes = toString.toIntOrNull()
                    if (sendTimes == null || sendTimes <= 0) {
                        mBinding.giftNumEdit.setText("")
                        return
                    }
                    if (sendTimes > 999) {
                        sendTimes = 999
                        mBinding.giftNumEdit.setText("999")
                        mBinding.giftNumEdit.setSelection(mBinding.giftNumEdit.text.toString().length)
                    }

                    giftSendBean?.apply {
                        this.num = sendTimes
                    }
                    getAdapter(mTitleAdapter.getSelectType())?.apply { updateTimes(sendTimes) }
                }
            }
        })
        //导航器联动
        mTitleList.forEach {
            it.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    mIndicator.setSelect(position)
                }
            })
        }
        mBinding.viewPageBackpack.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mIndicator.setSelect(position)
            }
        })

        mBinding.sendGift.setOnSingleClickListener {
            giftSendBean?.run {
                if (this.backpackType == BACKPACK_TOOL) {
                    ToastGravity.showGravity(StringUtils.getString(string.props_cannot_be_sent))
                    return@setOnSingleClickListener
                }
                val list = mutableListOf<Long>()
                if (mBinding.headRecycler.isVisible) {
                    list.addAll(mHeadAdapter.getSelectUser())
                } else {
                    mInfoOther?.userId?.let { it1 -> list.add(it1) }
                }
                if (isShowBackPack) { //背包礼物
                    backpackId?.let {
                        //更新礼物数量
                        mBinding.allTv.background = null
                        mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.fff_70))
                        if (list.isNotEmpty()) {
                            upBackpackIdCount(it, -num)
                        }
                        partySendGiftCallback?.invoke(this, list)
                        sendGiftCallback?.invoke(this)
                    }
                    isSend = true
                } else { //其他礼物
                    if (this.num >= 20 && this.gift.type == LiveConst.GiftType.NORMAL_GIFT && !isShowSendGiftSurePopup) {
                        isShowSendGiftSurePopup = true
                        SendGiftSurePopup.show(requireContext(), this) {
                            partySendGiftCallback?.invoke(this, list)
                            sendGiftCallback?.invoke(this)
                            isSend = true
                        }
                    } else {
                        partySendGiftCallback?.invoke(this, list)
                        sendGiftCallback?.invoke(this)
                        isSend = true
                    }

                }

            }
            //全部送出将选中数值变更为1 上次选中取消
            if (giftSendBean?.isAll == true) {
                mBinding.allTv.background = null
                mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.fff_70))
                mGiftPagerBackPackAdapter.reset()
                mNumAdapter.setSelect(0)
                giftSendBean = null
            }
            hide()
            cancelTime()
            dismiss?.invoke()
        }
        mBinding.llMoney.setOnSingleClickListener {
            if (ViewUtils.getAliveTopActivity() is MessageActivity) {
                GlobalPopupManager.showRechargePopup(
                    requireContext(),
                    mViewModel,
                    isNeedBottom = false, onRechargeOk = {
                        EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                    }
                )
            } else {
                if (mTitleAdapter.getSelectType() == DIALOG_GAME && mBinding.giftTitleRecycler.isVisible) {
                    GlobalPopupManager.showExchangeGamePopup(requireContext(), mViewModel)
                } else {
                    GlobalPopupManager.showRechargePopup(
                        requireContext(),
                        mViewModel,
                        isNeedBottom = true, onRechargeOk = {
                            EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                        }
                    )
                }
            }
        }
        //头像选中
        mHeadAdapter.setOnItemClickListener { _, _, position ->
            val item = mHeadAdapter.getItem(position)
            item.isSelect = !item.isSelect
            mHeadAdapter.notifyItemChanged(position)
            switchLinkage()
        }
        //switch全选
        mBinding.switchBtn.setOnCheckedChangeListener { buttonView, isSelected ->
            if (buttonView.isPressed) {
                if (isSelected) {
                    val list = mHeadAdapter.data
                    list.forEach {
                        if (!it.isSelect) {
                            it.isSelect = true
                        }
                    }
                    mBinding.tvSwitchAll.visibility = View.GONE

                } else {
                    val list = mHeadAdapter.data
                    list.forEach {
                        if (it.isSelect) {
                            it.isSelect = false
                        }
                    }
                    mBinding.tvSwitchAll.visibility = View.VISIBLE
                }
                mHeadAdapter.notifyDataSetChanged()
            }
        }
        ImNoticeManager.observeAccountChange(this) {
            updateCoinView()
        }
        ImNoticeManager.observeGameAccountChange(this) {
            updateCoinView()
        }
        //title切换
        mTitleAdapter.setOnItemClickListener { _, _, position ->
            val item = mTitleAdapter.getItem(position)
            //没有切换item
            if (item.type == mTitleAdapter.getSelectType()) return@setOnItemClickListener
            mTitleAdapter.setSelectType(item.type)//设置头部选择
            showViewPager(item.type)
            titleClick(item)
            val banner = giftSendBean?.gift?.banner
            showGiftBanner(banner)
        }
    }

    //使用道具
    private fun useConsumable(
        backpackId: Long,
        otherUserId: Long,
    ) {
        val useDressUp = UseConsumableRequest(backpackId, otherUserId, anchorId)
        mViewModel.requestLoading({ userService.useConsumable(useDressUp) }, { use ->
            ToastGravity.showGravity(use.showText)
            val userBackPackIndex = backPackList.indexOfFirst { it.backpackId == backpackId }
            if (userBackPackIndex != -1) {
                val userBackPackData = backPackList[userBackPackIndex]
                userBackPackData.let {
                    if (it.amount > 1) {
                        val bcr = it.getUserBackpackConsumableResp()
                        if (bcr != null) {
                            bcr.backpackIds.remove(backpackId)
                            bcr.expiredTimes.removeAt(0)
                            val newBackpackId = bcr.backpackIds.firstOrNull()
                            val newContext = JsonUtils.toJson(bcr)
                            val newAmount = bcr.backpackIds.size.toLong()
                            val newExpiredTime = bcr.expiredTimes.firstOrNull()
                            if (newBackpackId != null) {
                                val newData = it.copy(
                                    amount = newAmount,
                                    backpackId = newBackpackId,
                                    expiredTime = newExpiredTime,
                                    content = newContext
                                )
                                backPackList[userBackPackIndex] = newData
                            } else {
                                backPackList.remove(userBackPackData)
                            }
                        } else {
                            backPackList.remove(userBackPackData)
                        }
                    } else {
                        backPackList.remove(userBackPackData)
                    }
                }
                initTitleGiftBackPack(backPackList)
                getBackpackGifts(sourceType)
            }
        }, {
            ToastGravity.showGravity(it.errorMsg)
        })
    }

    /**
     * 顶部点击
     */
    private fun titleClick(data: GiftSendTitleBean) {
        giftSendBean = null
        updateCoinView()//更新用户的金币样式   有游戏币有钻石
        //隐藏自定义输入框
        switchGiftNumState(false)
        hideSoftInput()
        if (data.adapter.data.isEmpty()) {    //这个页面没有礼物数据
            mIndicator.setList(emptyList())
        } else {
            mIndicator.setList(Collections.nCopies(data.adapter.data.size, ""))
            val currentItem = data.viewPager2.currentItem
            mIndicator.setSelect(currentItem)

            val indexPage = data.adapter.getIndexPage()
            val selectPosition = data.adapter.getSelectPosition()
            if (indexPage == -1 || selectPosition == -1) { //没有选中任何礼物
                val twoData = data.adapter.data[0]
                if (twoData.isNotEmpty()) { //找到数据再设置为默认为0的位置
                    data.adapter.reset()
                    giftSendBean = GiftSendBean(BACKPACK_GIFT, twoData[0], 1)
                }
            } else {
                //这个页面选中的数据
                val selectData = data.adapter.data.getOrNull(indexPage)?.getOrNull(selectPosition)
                if (selectData != null) { //选中有效
                    data.adapter.updateTimes(1)
                    giftSendBean = GiftSendBean(BACKPACK_GIFT, selectData, 1)
                } else {
                    val twoData = data.adapter.data[0]
                    if (twoData.isNotEmpty()) { //找到数据再设置为默认为0的位置
                        data.adapter.reset()
                        giftSendBean = GiftSendBean(BACKPACK_GIFT, twoData[0], 1)
                    }
                }
            }
        }

        selectInit()
        mBinding.sourceTv.visibility = View.GONE
        isShowBackPack = false
        mBinding.allTv.visibility = View.GONE
        mBinding.giftSelectImg.visibility = View.VISIBLE
        mBinding.viewPageBackpack.visibility = View.GONE
        mBinding.knapsackImg.setImageResource(R.drawable.ic_knapsack_close)
    }

    private fun switchGiftNumState(isShowView: Boolean) {
        if (isShowView) {
            mBinding.giftSelectImg.visibility = View.GONE
            mBinding.giftNumEdit.visibility = View.VISIBLE
            mBinding.giftNumEdit.requestFocus()
        } else {
            if (mBinding.viewPageBackpack.visibility == View.VISIBLE) {
                mBinding.giftSelectImg.visibility = View.GONE
            } else {
                mBinding.giftSelectImg.visibility = View.VISIBLE
            }

            mBinding.giftNumEdit.visibility = View.GONE
            mBinding.giftNumEdit.setText("")
        }
    }

    private fun showSoftInput() {
        val imm =
            Utils.getApp().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mBinding.giftNumEdit, InputMethodManager.SHOW_IMPLICIT)
    }

    private fun hideSoftInput() {
        val imm =
            Utils.getApp().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view?.windowToken, 0)
    }

    /**
     * 处理选中的礼物
     */
    private fun selectedGiftId() {
        mTitleList.forEachIndexed outerLoop@{ _, titleBean ->
            titleBean.adapter.data.forEachIndexed { index, giftBeans ->
                if (giftBeans.isNotEmpty()) {
                    val giftBeanIndex = giftBeans.indexOfFirst { it.id == mGiftId }
                    if (giftBeanIndex != -1) { //找到了位置
                        isShowBackPack = false
                        val giftBean = giftBeans[giftBeanIndex]
                        giftSendBean = GiftSendBean(BACKPACK_GIFT, giftBean, 1)

                        titleBean.viewPager2.currentItem = index
                        titleBean.adapter.updateIndex(index, giftBeanIndex)

                        mTitleAdapter.setSelectType(titleBean.type)//设置头部选择
                        showViewPager(titleBean.type)
                        titleClick(titleBean)

                        mNumAdapter.setSelect(0)
                        return@outerLoop
                    }
                }
            }
        }
    }

    override fun onShow() {
        startTime()
        mBinding.allTv.background = null
        mBinding.allTv.setTextColor(ColorUtils.getColor(R.color.fff_70))
        if (giftSendBean != null && giftSendBean?.isSend == true) {
            if (isShowBackPack) {
                val index = mGiftPagerBackPackAdapter.getIndexPage()
                val position = mGiftPagerBackPackAdapter.getSelectPosition()
                if (index != -1 && position != -1) { //上次选择过
                    val page = mGiftPagerBackPackAdapter.getItemOrNull(index)
                    if (page != null) {
                        val data = page.getOrNull(position) //上次选中的位置
                        if (data == null || data.backpackId != giftSendBean?.backpackId) { //数据对不上选中本页第一个
                            giftSendBean = null
                            val pageOne = page.getOrNull(0)
                            if (pageOne != null) {
                                giftSendBean = GiftSendBean(
                                    pageOne.backpackType,
                                    pageOne.getGiftBeanNoNull(),
                                    1,
                                    backpackId = pageOne.backpackId
                                )
                                val banner = giftSendBean?.gift?.banner
                                showGiftBanner(banner)
                                setDescription(pageOne.description)
                                mGiftPagerBackPackAdapter.updateIndex(index, 0)
                                mGiftPagerBackPackAdapter.updateTimes(1)
                            } else { //本页第一个都没有  切换首页选第一个
                                setBackPackOneData()
                            }
                        } else {//数据正常
                            if (data.amount > NUM_LIST[NUM_LIST.size - 1]) {
                                selectInit()
                            } else {
                                mGiftPagerBackPackAdapter.updateTimes(1)
                                mNumAdapter.setSelect(0)
                            }
                            setDescription(data.description)
                        }
                    } else {//本页没有数据  切换首页选第一个
                        setBackPackOneData()
                    }
                } else {
                    setBackPackOneData()
                }

            } else {
                selectInit()
            }
        } else {
            if (isShowBackPack) {
                setBackPackOneData()
            } else {
                if (giftSendBean == null) {
                    mTitleList.getOrNull(0)?.apply {
                        adapter.let {
                            val data = it.data.getOrNull(0)
                            if (!data.isNullOrEmpty()) { //找到数据再设置为默认为0的位置
                                it.reset()
                                data.getOrNull(0)?.also { v ->
                                    showGiftBanner(v.banner)
                                    giftSendBean = GiftSendBean(BACKPACK_GIFT, v, 1)
                                }
                            }
                        }
                        viewPager2.currentItem = 0
                    }
                    mNumAdapter.setSelect(0)
                }
            }
        }

        if (mGiftId != -1L) { //有传需要选中的礼物
            selectedGiftId()
            mGiftId = -1L
        } else { //有传选中类型
            if (mGiftType != -1) {
                mTitleAdapter.data.find {
                    val type = when (it.type) {
                        DIALOG_LUCK -> LiveConst.GiftType.LUCK_GIFT
                        DIALOG_COMMON -> LiveConst.GiftType.NORMAL_GIFT
                        DIALOG_GAME -> LiveConst.GiftType.GAME_BEANS_GIFT
                        DIALOG_BACKPACK -> LiveConst.GiftType.LUCK_BACKPACK
                        DIALOG_CUSTOMIZED -> LiveConst.GiftType.CUSTOMIZED
                        DIALOG_GIFT_PRIVILEGE -> LiveConst.GiftType.GIFT_PRIVILEGE
                        else -> -1
                    }
                    type == mGiftType
                }?.let { item ->
                    //没有切换item
                    if (item.type == mTitleAdapter.getSelectType()) return
                    mTitleAdapter.setSelectType(item.type)//设置头部选择
                    showViewPager(item.type)
                    titleClick(item)
                    val banner = giftSendBean?.gift?.banner
                    showGiftBanner(banner)
                }
                mGiftType = -1
            }
        }
        updateCoinView()
    }

    private fun setDescription(description: String?) {
        if (description.isNullOrEmpty()) {
            mBinding.sourceTv.visibility = View.GONE
        } else {
            mBinding.sourceTv.visibility = View.VISIBLE
            mBinding.sourceTv.text = description
        }
    }

    /**
     * 设置数据为首页第一个
     */
    private fun setBackPackOneData() {
        giftSendBean = null
        val vPageOne = mGiftPagerBackPackAdapter.data.getOrNull(0)
        if (!vPageOne.isNullOrEmpty()) { //首页有第一个数据切换过去
            val item = vPageOne[0]
            mGiftPagerBackPackAdapter.reset()
            giftSendBean = GiftSendBean(item.backpackType, item.getGiftBeanNoNull(), 1, backpackId = item.backpackId)
            setDescription(item.description)
            mBinding.viewPageBackpack.currentItem = 0
        }
        mNumAdapter.setSelect(0)
    }

    //初始化数据并分页处理
    private fun initPage(list: List<GiftBean>, viewPager2: ViewPager2, mAdapter: GiftPagerAdapter) {
        val size = list.size
        var count = size / PAGE_GIFT_NUMBER
        if (size % PAGE_GIFT_NUMBER != 0) {
            ++count
        }
        val viewList = mutableListOf<List<GiftBean>>()
        val number = PAGE_GIFT_NUMBER
        for (i in 0 until count) {
            var lastIndex = (i + 1) * number
            if (lastIndex >= size) {
                lastIndex = size
            }
            viewList.add(list.subList(i * number, lastIndex))
        }
        viewPager2.apply {
            adapter = mAdapter.apply {
                setList(viewList)
            }
            offscreenPageLimit = max(1, count)

            (getChildAt(0) as RecyclerView).itemAnimator = null
        }
    }

    private fun selectInit() {
        giftSendBean?.let {
            if (it.num !in NUM_LIST) {
                mNumAdapter.setSelect(-1)
            } else {
                for (i in 0 until NUM_LIST.size) {
                    if (NUM_LIST[i] == it.num) {
                        mNumAdapter.setSelect(i)
                        break
                    }
                }
            }
        }
    }

    private fun updateCoinView() {
        if (mTitleAdapter.getSelectType() == DIALOG_GAME && mBinding.giftTitleRecycler.isVisible) {
            mBinding.ivGiftIcon.setImageResource(R.drawable.ic_game_beans)
            mBinding.myCoin.text = UserManager.getUser().account?.userGameCoins?.toString() ?: "0"
        } else {
            mBinding.ivGiftIcon.setImageResource(R.drawable.ic_diamond1)
            mBinding.myCoin.text = UserManager.getUser().account?.coins?.toString() ?: "0"
        }
    }

    fun setAvatar(avatar: String, avatarFrame: String? = null) {
        if (this::mBinding.isInitialized && context != null) {
            mBinding.llTitle.visibility = View.VISIBLE
            Glide.with(requireContext())
                .load(ImageUtils.imgPathSmall(avatar))
                .transform(CircleCrop())
                .into(mBinding.avatar)
            mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(avatarFrame))
        }
        mAvatar = avatar
        mAvatarFrame = avatarFrame
    }

    private fun showGiftBanner(banner: List<GiftBannerVo>? = null) {
        if (banner?.isNotEmpty() == true) {
            mBinding.giftBannerView.create(banner)
            mBinding.giftBannerView.visibility = View.VISIBLE
        } else {
            mBinding.giftBannerView.visibility = View.GONE
        }
    }

    /**
     * 设置选中的礼物Id
     */
    fun setSelectedGiftId(giftId: Long) {
        mGiftId = giftId
    }

    /**
     * 设置选中列表
     */
    fun setSelectedGiftType(giftType: Int) {
        mGiftType = giftType
    }

    /**
     * 派对送给某个人
     */
    fun setPartySomeOne(infoOtherResp: UserBasicVo) {
        mInfoOther = infoOtherResp
        if (this::mBinding.isInitialized && context != null) {
            mBinding.lookUserProfile.visibility = View.VISIBLE
            mBinding.avFv.visibility = View.VISIBLE
            mBinding.consSwitch.visibility = View.GONE
            mBinding.headRecycler.visibility = View.GONE
        }
    }

    /**
     * 派对送给麦上的人
     */
    fun setPartyAll(seatList: List<BaseSeatBean>, homeOwner: Long) {
        mSeatList = seatList.toMutableList()
        mHomeOwner = homeOwner
        if (this::mBinding.isInitialized && context != null) {

            mBinding.llTitle.visibility = View.VISIBLE
            mBinding.headRecycler.visibility = View.VISIBLE
            mBinding.consSwitch.visibility = View.VISIBLE
            mBinding.switchBtn.visibility = View.VISIBLE
            mBinding.tvSwitchAll.visibility = View.VISIBLE
            mBinding.lookUserProfile.visibility = View.GONE
            mBinding.avFv.visibility = View.GONE
            mBinding.switchBtn.isChecked = false
            val list = mutableListOf<GiftSeatBean>()
            seatList.forEachIndexed { index, seatBean ->
                val userBasicVo = seatBean.userBasicVo
                if (!userBasicVo?.avatar.isNullOrEmpty()) {
                    list.add(GiftSeatBean(seatBean, list.isEmpty()))
                }
            }
            mHeadAdapter.setHomeOwner(homeOwner)
            mHeadAdapter.setList(list)
            switchLinkage()
        }
    }

    fun setUserId(otherId: Long, name: String?) {
        mOtherId = otherId
        mOtherName = name
        if (this::mBinding.isInitialized && context != null) {
            if (showType == AppConst.GiftComming.LIVE || showType == AppConst.GiftComming.CALL) {
                mBinding.lookUserProfile.visibility = View.GONE
            } else {
                mBinding.lookUserProfile.visibility = View.VISIBLE
            }
        }
    }

    private fun switchLinkage() {
        //如果手动点击头像  判断是否全选了，如果全选了就跟swich联动
        val selectItems = mHeadAdapter.data.filter { it.isSelect }
        if (selectItems.size == mHeadAdapter.data.size) {
            if (!mBinding.switchBtn.isChecked) {
                mBinding.switchBtn.isChecked = true
                mBinding.tvSwitchAll.visibility = View.GONE
            }
        } else {
            if (mBinding.switchBtn.isChecked) {
                mBinding.switchBtn.isChecked = false
                mBinding.tvSwitchAll.visibility = View.VISIBLE
            }
        }
    }

    //筛选礼物
    private fun filterGift(type: Int): List<GiftBean> {
        val tempList =
            mData.filter { gift -> gift.type == type }
        return tempList.distinctBy { "${it.id}${it.payload}" }
    }

    override fun getTopMargin(): Int {
        return super.getTopMargin() - 20.dp
    }

    /**
     * 初始化背包列表 并设置进去
     */
    private fun initTitleGiftBackPack(mData: List<UserBackpackGiftResp>) {
        backPackList = mData.toMutableList()

        val size = mData.size
        var count = size / PAGE_GIFT_NUMBER
        if (size % PAGE_GIFT_NUMBER != 0) {
            ++count
        }
        val viewList = mutableListOf<List<UserBackpackGiftResp>>()
        val number = PAGE_GIFT_NUMBER
        for (i in 0 until count) {
            var lastIndex = (i + 1) * number
            if (lastIndex >= size) {
                lastIndex = size
            }
            viewList.add(mData.subList(i * number, lastIndex))
        }
        mGiftPagerBackPackAdapter.setList(viewList)
    }

    /**
     * 获取分类礼物  常规
     */
    private fun getGiftList(position: Int): List<GiftBean> {
        return when (position) {
            DIALOG_LUCK -> filterGift(LiveConst.GiftType.LUCK_GIFT)
            DIALOG_COMMON -> filterGift(LiveConst.GiftType.NORMAL_GIFT)
            DIALOG_GAME -> filterGift(LiveConst.GiftType.GAME_BEANS_GIFT)
            DIALOG_CUSTOMIZED -> filterGift(LiveConst.GiftType.CUSTOMIZED)
            DIALOG_GIFT_PRIVILEGE -> filterGift(LiveConst.GiftType.GIFT_PRIVILEGE)
            else -> emptyList()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        timeJob?.cancel()
        timeJob = null
    }

    private fun showGuide() {
        //当他不是派对房 也不是 游戏房 那就不要继续了 sourceType是来源
        if (sourceType !in listOf(AppConst.BackpackGiftComming.PARTY, AppConst.BackpackGiftComming.PARTY_GAME)) return
        //如果这个id出现过引导那就不要继续了
        val userPartyGiftTag = CommonCache.getUserPartyGiftTag()
        if (userPartyGiftTag.toBoolean()) return
        //获取头像列表的第一个  和  礼物列表的第一个

        val viewPage = if (isShowBackPack) {
            mBinding.viewPageBackpack
        } else {
            mTitleList.find { it.viewPager2.visibility == View.VISIBLE }?.viewPager2
        }
        val get = viewPage?.get(0) as? RecyclerView ?: return
        val headView = mBinding.headRecycler.findViewHolderForAdapterPosition(0) ?: return
        val giftRecycler = get.findViewHolderForAdapterPosition(0)
        val giftView = (giftRecycler?.itemView as RecyclerView).findViewHolderForAdapterPosition(0) ?: return

        if (headView is BaseViewHolder && giftRecycler is BaseViewHolder) {
            mViewModel.viewModelScope.launch {
                delay(500)//延迟500毫秒等待弹窗动画结束
                HighlightPro.with(dialog?.window?.decorView as FrameLayout)
                    .setHighlightParameter {
                        HighlightParameter.Builder()
                            .setHighlightView(headView.itemView)
                            .setHighlightShape(RectShape())
                            .setTipsViewId(if (AppCodeUtils.isAR()) R.layout.layout_hight_tips_view_ar else R.layout.layout_hight_tips_view)
                            .setMarginOffset(
                                MarginOffset(
                                    start = if (AppCodeUtils.isAR()) -(350).autoDp else -(50).autoDp,
                                )
                            )
                            .setConstraints(Constraints.StartToStartOfHighlight + Constraints.BottomToTopOfHighlight)
                            .build()
                    }
                    .setHighlightParameter {
                        HighlightParameter.Builder()
                            .setHighlightView(giftView.itemView)
                            .setHighlightShape(RectShape())
                            .setTipsViewId(R.layout.layout_hight_tips_two_view)
                            .setMarginOffset(
                                MarginOffset(
                                    start = if (AppCodeUtils.isAR()) -(350).autoDp else 0,
                                )
                            )
                            .setConstraints(Constraints.StartToStartOfHighlight + Constraints.BottomToTopOfHighlight)
                            .build()
                    }
                    .setHighlightParameter {
                        HighlightParameter.Builder()
                            .setHighlightView(mBinding.llNumSend)
                            .setHighlightShape(RectShape())
                            .setTipsViewId(R.layout.layout_hight_tips_three_view)
                            .setMarginOffset(MarginOffset(start = -(25).autoDp.arReverse))
                            .setConstraints(Constraints.StartToStartOfHighlight + Constraints.BottomToTopOfHighlight)
                            .build()
                    }
                    .setBackgroundColor(ColorUtils.getColor(R.color.color_000_85))
                    .setOnShowCallback { }
                    .setOnDismissCallback {}
                    .interceptBackPressed(true)
                    .show()
            }
            //存储记忆这个用户执行过了引导逻辑
            CommonCache.saveUserPartyGiftTag()
        }

    }

    companion object {

        const val FRAGMENT_TAG = "GiftDialogFragment"

        /**
         * 背包类型
         *
         * 2 - 礼物
         * 3 - 道具
         */

        private const val BACKPACK_GIFT = 2L
        private const val BACKPACK_TOOL = 3L

        private const val PAGE_GIFT_NUMBER = 8

        private val NUM_LIST = mutableListOf(
            1, 7, 21, 51, 101,
        )
        const val DIALOG_LUCK = 0
        const val DIALOG_COMMON = 1
        const val DIALOG_GAME = 2
        const val DIALOG_BACKPACK = 3
        const val DIALOG_CUSTOMIZED = 4
        const val DIALOG_GIFT_PRIVILEGE = 5
    }
}